(function () {
    // Initialize the variable that store the objects.
    var overrideCtx = {};
    overrideCtx.Templates = {};

    // Assign functions or plain html strings to the templateset objects:
    // header, footer and item.
    /*overrideCtx.Templates.Header = "<B><#=ctx.ListTitle#></B>" +
        "<hr><ul id='unorderedlist'>";*/

    // This template is assigned to the CustomItem function.
    // overrideCtx.Templates.Item = customItem;
    /* overrideCtx.Templates.Footer = "</ul>";*/

    // Set the template to the:
    //  Custom list definition ID
    //  Base view ID
     overrideCtx.BaseViewID = 2;
     overrideCtx.ListTemplateType = 10057;

    // Assign a function to handle the
    // PreRender and PostRender events
    overrideCtx.OnPreRender = preRenderHandler;
    overrideCtx.OnPostRender = postRenderHandler;

    // Register the template overrides.
    SPClientTemplates.TemplateManager.RegisterTemplateOverrides(overrideCtx);
})();

var listData;
// This function builds the output for the item template,
// it uses the context object to access announcement data.
function customItem(ctx) {

    // Build a listitem entry for every announcement in the list.
    var ret = "<li>" + ctx.CurrentItem.Title + "</li>";
    return ret;
}

// The preRenderHandler handles the 
// OnPreRender event
function preRenderHandler(ctx) {

    // Override the default title with user input
    // ctx.ListTitle = prompt("Type a title", ctx.ListTitle);
}

// The postRenderHandler handles the 
// OnPostRender event
function postRenderHandler(ctx) {
    listData = ctx.ListData;
    ExecuteOrDelayUntilScriptLoaded(RefreshReadMark, "sp.js");
}

// Used for storing list item collection which return by caml query
var collListItem;
var readMarkPlaceHolders;

// Refresh read mark for the list view
function RefreshReadMark()
{
    readMarkPlaceHolders = $(".ReadMarkFiledPlaceHloderClass");
    var clientContext = new SP.ClientContext();
    var targetList = clientContext.get_web().get_lists().getByTitle("ReadList");
    var query = new SP.CamlQuery();
    query.set_viewXml(GenerateCaml(readMarkPlaceHolders));

    collListItem = targetList.getItems(query);
    clientContext.load(collListItem, "Include(Title,ID)");
    clientContext.executeQueryAsync(
         Function.createDelegate(this, onCamlQuerySucceeded),
         Function.createDelegate(this, onCamlQueryFailed)
        );
}

// Generate the caml 
function GenerateCaml(readMarkPlaceHolders) {
    var values ='';
    readMarkPlaceHolders.each(function () {
        values += " <Value Type = \'Text\'>" + $(this)[0].id + " </Value>"
    });

    return '<View><Query><Where><In><FieldRef Name=\'Title\'/>' +
        '<Values>' + values +
        '</Values></In></Where></Query>' +
        '<RowLimit>200</RowLimit></View>';
}

function onCamlQuerySucceeded(sender, args)
{
    // Set all rows fontWeight to bold implies these rows are unread
    readMarkPlaceHolders.each(function () {
        $(this)[0].innerText = "Unread";
        var parentTR = getParentNode_TR($(this)[0].parentNode);
        parentTR.style.fontWeight = 'bold';
        
    });

    var listItemEnumerator = collListItem.getEnumerator();

    // Set the rows(which is read) fontWeight to normal implies these rows are read
    while (listItemEnumerator.moveNext()) {
        var readItem = listItemEnumerator.get_current();       
        var currentReadMarkPlaceHolder = document.getElementById(readItem.get_item('Title'));
        currentReadMarkPlaceHolder.innerText = "Read";
        var currentParentTR = getParentNode_TR(currentReadMarkPlaceHolder.parentNode);
        currentParentTR.style.fontWeight = 'normal';

        for (index = 0; index < listData.Row.length; index++) {
            var currentRow = listData.Row[index];
            if (currentRow.Readed == readItem.get_item('Title')) {

                // Set the readed to 1 implies that row has been read by the current user
                // and the unread button in the rbbion area will be enable for this item(row)
                // unread context menu will be enable for this item(row)
                currentRow.Readed = '1';
                currentRow.readItemId = readItem.get_item('ID');
            }
        }
    }
}

// Handle the  caml query failed event
function onCamlQueryFailed(sender, args) {
    alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
}

// Get the elelemt's TR parent
function getParentNode_TR(parent) {
    while (parent && parent.tagName != 'TR') {
        parent = parent.parentNode;
    }

    return parent;
}

